package com.example.sixtrainingdemo.view;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sixtrainingdemo.R;
import com.example.sixtrainingdemo.adapter.ShopAdapter;
import com.example.sixtrainingdemo.adapter.ShopListAdapter;
import com.example.sixtrainingdemo.database.DBHelper;
import com.example.sixtrainingdemo.entity.Goods;
import com.example.sixtrainingdemo.entity.Shop;

import java.util.ArrayList;
import java.util.List;

public class ShopActivity extends AppCompatActivity {

    private ListView listView; // 声明 ListView 成员变量
    private DBHelper dbHelper;
    private ShopListAdapter adapter; // 使用ShopListAdapter

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_list);

        listView = findViewById(R.id.lv_shop);
        dbHelper = DBHelper.getInstance(this);

        // 获取传递过来的商品ID
        int goodsId = getIntent().getIntExtra("GOODS_ID", -1); // 0 为默认值，如果未找到商品ID

        // 查询数据库获取Goods对象
        Goods goods = dbHelper.selectAllGoods(goodsId);
        if (goods != null) {
            // 将Goods对象转换为Shop对象
            Shop shop = new Shop();
            shop.setId(goods.getId());
            shop.setName(goods.getName());
            shop.setPrice(goods.getPrice());
            shop.setUnit(goods.getUnit());
            // shop.setBrowseCount(goods.getBrowseCount()); // 如果Shop类中有这个属性
            // shop.setMessage(goods.getMessage()); // 如果Shop类中有这个属性

            int newRowId = dbHelper.insertShop(shop);
            if (newRowId > 0) {
                Log.d("ShopActivity", "Shop inserted successfully with row ID: " + newRowId);
            } else {
                Log.e("ShopActivity", "Failed to insert Shop.");
            }

            // 接下来，你可以更新你的ListView，如果需要的话
            // ...


            // 查询数据库获取Shop对象列表
            List<Shop> shopList = dbHelper.selectAllShop(); // 确保这个方法返回Shop对象列表
            // 将新创建的Shop对象添加到列表中
                //shopList.add(shop);
            // 创建ShopListAdapter的实例并设置给ListView
            adapter = new ShopListAdapter(this, shopList);
            listView.setAdapter(adapter);
        } else {
            // 如果没有找到商品，可以给用户一些反馈，例如显示一个消息
//                TextView emptyView = findViewById(R.id.empty_view); // 假设你有一个空视图用于显示消息
//                emptyView.setText("没有找到商品信息");
        }
    }

    private void updateListView() {
        // 刷新数据的逻辑，例如重新查询数据库并更新adapter的数据
        List<Shop> shopList = dbHelper.selectAllShop();
        adapter.updateData(shopList); // 假设你的adapter有一个updateData方法来更新数据
        adapter.notifyDataSetChanged(); // 通知数据已改变
    }



}
